#!/bin/bash

if [ ! $PROJECT_PATH ]; then
    PROJECT_PATH=$(cd $(dirname $0); pwd)
    echo "PROJECT_PATH SET $PROJECT_PATH"
else
    echo "PROJECT_PATH IS $PROJECT_PATH"
fi

if [ ! $TARGET_NAME ]; then
    TARGET_NAME="Hermes"
    echo "TARGET_NAME SET Hermes"
else
    echo "TARGET_NAME IS $TARGET_NAME"
fi

if [ ! $PROJECT_TYPE ]; then
    PROJECT_TYPE="xcworkspace"
    echo "PROJECT_TYPE SET xcworkspace"
else
    echo "PROJECT_TYPE IS $PROJECT_TYPE"
fi

# 打包环境 Release / Debug
CONFIGURATION=Release

#工程文件路径
APP_PATH="${PROJECT_PATH}/${TARGET_NAME}.$PROJECT_TYPE"

# Xcode clean
xcodebuild clean -workspace "${APP_PATH}" -configuration "${CONFIGURATION}" -scheme "${TARGET_NAME}"

# 时间戳
CURRENT_TIME=$(date "+%Y-%m-%d:%H-%M-%S")

# 导出路径
EXPORT_PATH="${CONFIGURATION}/${TARGET_NAME}-${CURRENT_TIME}"

# 归档路径
ARCHIVE_PATH="${EXPORT_PATH}/${TARGET_NAME}.xcarchive"

# plist路径
PLIST_PATH="${PROJECT_PATH}/exportPlist_mac.plist"

# archive 这边使用的工作区间 也可以使用project
xcodebuild archive -workspace "${APP_PATH}" -scheme "${TARGET_NAME}" -configuration "${CONFIGURATION}" -archivePath "${ARCHIVE_PATH}"

# 导出ipa
xcodebuild -exportArchive -archivePath "${ARCHIVE_PATH}" -exportPath "${EXPORT_PATH}" -exportOptionsPlist "${PLIST_PATH}"

#rename ipa
CURRENT_PATH=`pwd`
APP_VERSION=`defaults read $CURRENT_PATH/${TARGET_NAME}/Info CFBundleShortVersionString`
BUILD_NUMBER=`defaults read $CURRENT_PATH/${TARGET_NAME}/Info CFBundleVersion`

IPA_NAME=${TARGET_NAME}_for_Mac_v${APP_VERSION}.${BUILD_NUMBER}.ipa
mv $EXPORT_PATH/${TARGET_NAME}.ipa ${CONFIGURATION}/${IPA_NAME}

rm -rvf ${EXPORT_PATH} >/dev/null

rm -rvf ${SDK_PATH} >/dev/null

rm -rvf ${SDK_NAME} >/dev/null
